<!--
*  2021-03-15
*  纱线盘点入库
-->
<template>
  <div id="app" class="weaving-warehouse">
    <!-- 头部导航 -->
    <van-nav-bar
      :title="title"
      ref="header"
      left-text="返回"
      left-arrow
      @click-left="onClickLeft"
    >
      <template #right>
        <van-icon name="scan" size="20" @click="onClickRight" />
      </template>
    </van-nav-bar>
    <better-scroll class="weaving-warehouse__scroll public-scroll">
      <van-cell-group>
        <van-cell title="编号">
          <template>
            <van-search
              v-model="no"
              type="text"
              placeholder="输入编号"
              clearable
              ref="fieldInput"
            ></van-search>
          </template>
        </van-cell>
        <van-cell title="区域" is-link :value="stockArea"> </van-cell>
        <van-cell title="名称">
          <template>
            <van-field
              v-model="colorName"
              placeholder="输入名称"
              clearable
            ></van-field>
          </template>
        </van-cell>
        <van-cell title="批次号">
          <template>
            <van-field
              v-model="lotNum"
              placeholder="输入名称"
              clearable
            ></van-field>
          </template>
        </van-cell>
        <van-cell title="实际库存">
          <template>
            <van-field
              v-model="stock"
              type="tel"
              placeholder="实际库存"
              clearable
            ></van-field>
          </template>
        </van-cell>

        <van-cell title="打印数量">
          <template>
            <van-field
              v-model="printCount"
              type="tel"
              placeholder="输入数量"
              clearable
              @focus="onFocus"
              @blur="onBlur"
            ></van-field>
          </template>
        </van-cell>
      </van-cell-group>
      <van-cell-group class="weaving-warehouse-btn">
        <van-button block type="info" class="bgColor" @click="onClickPrint"
          >打印</van-button
        >
      </van-cell-group>
    </better-scroll>

    <van-popup v-model="showPicker" position="bottom">
      <van-picker
        show-toolbar
        value-key="no"
        :columns="columns"
        @confirm="onConfirm"
        @cancel="onCancel"
      />
    </van-popup>

    <van-popup v-model="showPickerArea" position="bottom">
      <van-picker
        show-toolbar
        :columns="stockAreaColumns"
        @confirm="onConfirmArea"
        @cancel="onCancel"
      />
    </van-popup>
  </div>
</template>

<script>
import { comeBack } from "@/utils/index";
import {
  getYarnStandardFilter,
  getByType,
  getYarnStockByYarnId,
  getYarnStoreByStoreId,
} from "@/api/yarn";
import dayjs from "dayjs";
import { getMacAddress } from "@/utils/auth";

export default {
  name: "weavingPrint",
  data() {
    return {
      title: "纱线盘点记录打印",
      no: "",
      yarnId: "",
      name: "",
      lotNum: "",
      unitFormat: 1,
      stock: "",
      expectStock: "",
      printCount: 1,
      printStatus: false,
      showPicker: false,
      columns: [],
      timeout: null,
      printRow: "",
      showStatus: false,
      actMoistureRegain: "",
      connectionStatus: false,
      stockArea: "",
      stockAreaColumns: [],
      showPickerArea: false,
      totalNum: 0,
      thickStock: "",
      putWeightTotal: "",
      planWeightTotal: "",
      weightTotal: "",
      expectOutTotal: "",
      colorName: ''
    };
  },
  watch: {
    // 监听编号
    // no(oldVal, newVal) {
    //   if (newVal && !this.showStatus) {
    //     // 防止input连续输入时，频繁发请求
    //     clearTimeout(this.timeout);
    //     this.timeout = setTimeout(() => {
    //       // 筛选
    //       if (oldVal !== newVal) {
    //         this.onSearch();
    //       }
    //     }, 1500);
    //   }
    // },
    // 监听弹窗
    showPicker(bool) {
      if (!bool && !this.showStatus) {
        this.$refs.fieldInput.focus();
      }
    },
  },
  created() {
    const that = this;
    if (process.env.NODE_ENV === "production") {
      this.$nextTick(() => {
        that.initFn(that);
      });
    } else {
      window.apiready = function () {
        that.initFn(that);
      };
    }
  },
  methods: {
    //初始化
    initFn(that) {
      if (getMacAddress()) {
        that.isEnabledBluetooth();
      } else {
        that.$toast.fail('如需打印，请退出登录选择打印机')
      }
      that.onGetTableList();
      window.api.addEventListener({
        name:'viewdisappear'
      }, function() {
        window.api.closeWin();
      });
    },
    // 返回
    onClickLeft() {
      comeBack();
    },
    // 扫码
    onClickRight() {
      const that = this;
      const zyHmsScan = api.require('zyHmsScan');
      zyHmsScan.openDefaultView({}, ret => {
        if(ret.status) {
          let id = ret.result;
          if (id.indexOf(",") != -1) {
            if (!that.$isJSON(id) || id.indexOf(",") == -1) {
              that.$toast.fail("二位码异常");
              return false;
            }
            let ids = eval(id);
            if (ids.toString().indexOf(",") == -1) {
              that.$toast.fail("二位码异常");
              return false;
            }
            id = ids.split(",")[0];
          }

          getYarnStoreByStoreId(id.toString(), (res) => {
            that.no = res.no;
            that.stockArea = res.stockArea;
            that.name = res.name;
            that.colorName = res.colorName;
            that.lotNum = res.lotNum || "";
            that.stock = res.stock;
            that.printRow = {
              id: id,
              yarnId: '',
              lotNum: res.lotNum || "",
              no: res.no,
              name: res.name,
              colorName: res.colorName,
              standard: res.standard,
              checkerName: res.checkerName || "",
              stock: res.stock,
              stockArea: res.stockArea,
            };
          });
        }
      });
    },
    // 获取编号
    onSearch() {
      this.columns = [];
      getYarnStandardFilter(
        {
          standard: this.no,
        },
        (res) => {
          if (res.code) {
            this.$toast.fail("筛选无数据");
            this.showPicker = false;
            this.$refs.fieldInput.focus();
          } else {
            this.$refs.fieldInput.blur();
            res.forEach((item) => {
              let params = {};
              params.no = item.no;
              params.yarnId = item.id;
              params.name = item.colorName;
              this.columns.push(params);
            });
            if (this.no) {
              this.showPicker = true;
            }
          }
        }
      );
    },
    // 获取区域
    onGetTableList() {
      this.stockAreaColumns = [];
      getByType(
        {
          pageSize: 1000,
          type: 9,
        },
        (res) => {
          this.stockArea = res.list[0].propertyValue;
          res.list.forEach((item) => {
            this.stockAreaColumns.push(item.propertyValue);
          });
        }
      );
    },
    onConfirmArea(val) {
      this.stockArea = val;
      this.showPickerArea = false;
    },
    // 打印数量获取焦点
    onFocus() {
      this.printCount = "";
    },
    onBlur() {
      this.printCount = this.printCount === "" ? 1 : this.printCount;
    },
    onClickFocus() {
      this.showStatus = false;
    },
    // 确认编号
    onConfirm(val) {
      this.showStatus = true;
      this.no = val.no;
      this.name = val.colorName;
      this.yarnId = val.yarnId;
      this.showPicker = false;
      getYarnStockByYarnId(
        {
          yarnId: this.yarnId,
        },
        (res) => {
          this.stockArea = res.stockArea;
          this.name = res.name;
          this.stock = res.stock;
          this.expectStock = res.expectStock;
          this.thickStock = res.thickStock;
          this.putWeightTotal = res.putWeightTotal;
          this.planWeightTotal = res.planWeightTotal;
          this.weightTotal = res.weightTotal;
          this.expectOutTotal = res.expectOutTotal;
          this.lotNum = res.lotNum;
          this.printRow = {
            id: res.id,
            yarnId: this.yarnId,
            no: res.no,
            name: res.colorName,
            standard: res.standard,
            lotNum: res.lotNum,
            checkerName: res.checkerName,
          };
        }
      );
    },
    // 打印
    onClickPrint() {
      const that = this;
      if (!that.connectionStatus) {
        // 先连接
        that.connectBleByMacAddress(true);
        return false;
      }
      --that.printCount;
      that.printStatus = true;
      that.$toast({
        type: "success",
        message: "打印中",
        duration: 1000,
        onClose: () => {
          this.getConnectState();
          // if (that.printCount <= 0) {
          //   that.no = "";
          //   that.yarnId = "";
          //   that.actMoistureRegain = "";
          //   that.stock = "";
          //   that.name = "";
          //   that.expectStock = "";
          //   that.thickStock = "";
          //   that.putWeightTotal = "";
          //   that.planWeightTotal = "";
          //   that.weightTotal = "";
          //   that.expectOutTotal = "";
          //   that.printRow = {}
          //   that.printCount = 1;
          // } else {
          //   that.onClickPrint();
          // }
        },
      });
    },
    onCancel() {
      this.yarnId = "";
      this.showPickerArea = false;
      this.showPicker = false;
    },
    // 判断蓝牙是否打开
    isEnabledBluetooth() {
      const that = this;
      window.api
        .require("cxgBluetoothBase")
        .isEnabledBluetooth({}, (ret, err) => {
          if (!err) {
            if (ret.state) {
              // 已打开
              that.connectBleByMacAddress();
            } else {
              that.openBluetooth();
            }
          } else {
            that.$toast.fail("code: " + err.code + " msg: " + err.msg);
          }
        });
    },
    // 打开蓝牙
    openBluetooth() {
      const that = this;
      window.api
        .require("cxgBluetoothBase")
        .openBluetooth({}, function (ret, err) {
          if (!err) {
            if (ret.state) {
              // 已打开
              that.connectBleByMacAddress();
            }
          } else {
            that.listenBluetoothStatus();
          }
        });
    },
    // 监听蓝牙连接状态
    listenBluetoothStatus() {
      const that = this;
      window.api
        .require("cxgBluetoothBase")
        .listenBluetoothStatus({}, function (ret, err) {
          if (!err) {
            if (ret.status === "STATE_ON") {
              that.connectBleByMacAddress();
            }
          } else {
            that.$toast.fail("code: " + err.code + " msg: " + err.msg);
          }
        });
    },
    // 查询打印机连接状态
    getConnectState() {
      const that = this;
      that.$toast({
        message: "正在打印",
        type: "loading",
        duration: 20000,
      });
      var obj = window.api.require("xGprinterPlus");
      var ret = obj.getConnectState();
      if (ret.status) {
        let result = false;
        ret.state.forEach((bool) => {
          if (bool) {
            result = bool;
          }
        });
        if (result) {
          // 已连接
          that.$toast.clear();
          if (that.printStatus) {
            that.printLabel();
          }
        } else {
          // 未连接
          that.$toast({
            type: "fail",
            message: "未连接, 请等待",
            duration: 1500,
            onClose: () => {
              that.connectBleByMacAddress();
            },
          });
        }
      } else {
        // 未连接
        that.$toast({
          type: "fail",
          message: "未连接, 请等待",
          duration: 1500,
          onClose: () => {
            that.connectBleByMacAddress();
          },
        });
      }
    },
    // 连接蓝牙
    connectBleByMacAddress(status) {
      const that = this;
      if (that.printStatus) {
        that.$toast({
          message: "初始化打印机",
          type: "loading",
          duration: 20000,
        });
      }
      var demo = window.api.require("xGprinterPlus");
      demo.connectBleByMacAddress(
        {
          macAddress:  getMacAddress() ? getMacAddress().address : '',
        },
        function (ret, err) {
          if (ret.status) {
            if (ret.message === "已连接") {
              that.connectionStatus = true;
              if (that.printStatus) {
                that.$toast({
                  type: "success",
                  message: "连接成功",
                  duration: 1500,
                  onClose: () => {
                    that.printLabel();
                  },
                });
              }
              if (status) {
                that.onClickAddStore();
              }
            } else if (ret.message === "连接失败") {
              that.connectionStatus = false;
              that.$toast({
                type: "fail",
                message: "初始化失败",
                duration: 1500,
              });
            } else {
              that.connectionStatus = false;
            }
          } else {
            that.$toast({
              type: "fail",
              message: err.msg,
              duration: 1500,
            });
          }
        }
      );
    },
    // 打印数据
    printLabel() {
      const that = this;
      var obj = window.api.require("xGprinterPlus");
      obj.printLabel(
        {
          rows: [
            {
              lineType: "size",
              width: 50,
              height: 70,
            },
            {
              lineType: "gap",
              data: 3,
            },
            {
              lineType: "cls",
            },
            {
              // 图片单元格竖线
              lineType: "bar",
              x: 25 + 130,
              y: 0,
              width: 2,
              height: 136,
            },
            {
              //绘制图片
              lineType: "image",
              x: 25 + 8,
              y: 8,
              data: "widget://image/huibo_logo.png",
            },
            {
              //绘制文本
              lineType: "text",
              x: 25 + 8,
              y: 10,
              rotation: 0,
              xscal: 1,
              yscal: 1,
              data: "艺多染整",
            },
            {
              //绘制文本
              lineType: "text",
              x: 25 + 8,
              y: 60,
              rotation: 0,
              xscal: 1,
              yscal: 2,
              data: "盘库单",
            },
            {
              lineType: "qrcode", // 绘制qrcode
              x: 25 + 170 + 2,
              y: 10,
              level: "L", //L|M|H|Q
              cellwith: 5,
              rotation: 0, // 0|90|180|270
              data: that.printRow.id.toString(),
            },
            {
              // 横线
              lineType: "bar",
              x: 25 + 4,
              y: 136,
              width: 156,
              height: 2,
            },
            {
              //绘制文本
              lineType: "text",
              x: 25 + 4,
              y: 136 + 2,
              rotation: 0,
              xscal: 1,
              yscal: 2,
              data: dayjs().format("YYYY-MM-DD"),
            },
            {
              //绘制文本
              lineType: "text",
              x: 25 + 130 + 4,
              y: 136 + 2,
              rotation: 0,
              xscal: 1,
              yscal: 2,
              data: "批次号：" + that.lotNum,
            },
            {
              // 横线
              lineType: "bar",
              x: 25,
              y: 186,
              width: 608,
              height: 2,
            },
            {
              //绘制文本
              lineType: "text",
              x: 25 + 4,
              y: 186 + 2,
              rotation: 0,
              xscal: 1,
              yscal: 2,
              data: "编号: " + that.printRow.no,
            },
            {
              // 横线
              lineType: "bar",
              x: 25,
              y: 236,
              width: 608,
              height: 2,
            },
            {
              //绘制文本
              lineType: "text",
              x: 90 + 4,
              y: 236 + 2,
              rotation: 0,
              xscal: 1,
              yscal: 2,
              data:
                that.printRow.no.length > 22
                  ? that.printRow.no.substr(22, that.printRow.no.length)
                  : "",
            },
            {
              // 横线
              lineType: "bar",
              x: 25,
              y: 286,
              width: 608,
              height: 2,
            },
            {
              //绘制文本
              lineType: "text",
              x: 25 + 4,
              y: 286 + 2,
              rotation: 0,
              xscal: 1,
              yscal: 2,
              data: "颜色: " + that.printRow.colorName,
            },
            {
              //绘制文本
              lineType: "text",
              x: 25 + 4,
              y: 336 + 2,
              rotation: 0,
              xscal: 1,
              yscal: 2,
              data: "规格: " + that.printRow.standard,
            },
            {
              // 横线
              lineType: "bar",
              x: 25,
              y: 336,
              width: 608,
              height: 2,
            },
            {
              //绘制文本
              lineType: "text",
              x: 25 + 4,
              y: 386 + 2,
              rotation: 0,
              xscal: 1,
              yscal: 2,
              data: "重量: " + that.stock + "KG",
            },
            {
              // 横线
              lineType: "bar",
              x: 25,
              y: 386,
              width: 608,
              height: 2,
            },
            {
              //绘制文本
              lineType: "text",
              x: 25 + 4,
              y: 436 + 2,
              rotation: 0,
              xscal: 1,
              yscal: 2,
              data: "操作人: " + that.printRow.checkerName,
            },
            {
              // 横线
              lineType: "bar",
              x: 25,
              y: 436,
              width: 608,
              height: 2,
            },
          ],
        },
        function (ret, err) {
          if (ret.status) {
            that.$toast.success("打印成功");
            if (that.printCount <= 0) {
              that.no = "";
              that.yarnId = "";
              that.actMoistureRegain = "";
              that.stock = "";
              that.name = "";
              that.expectStock = "";
              that.thickStock = "";
              that.putWeightTotal = "";
              that.planWeightTotal = "";
              that.weightTotal = "";
              that.expectOutTotal = "";
              that.printRow = {};
              that.printCount = 1;
            } else {
              that.onClickPrint();
            }
          } else {
            that.$toast({
              type: "fail",
              message: err.code + err.msg,
              duration: 1500,
              onClose: () => {
                that.connectBleByMacAddress();
              },
            });
          }
        }
      );
    },
  },
};
</script>

<style lang="scss">
.weaving-warehouse {
  display: flex;
  flex-direction: column;
  // padding-top: 22px;
  .weaving-warehouse__scroll {
    height: calc(100vh - 70px);
    overflow: hidden;
  }
  .van-cell {
    .van-cell__value {
      flex: 0 0 70%;
      .van-field {
        padding: 0;
        display: flex;
        .van-cell__value {
          flex: 1;
        }
        .van-field__control {
          text-align: right;
        }
      }
      .van-search {
        padding: 0;
        .van-field__left-icon {
          display: flex;
          align-items: center;
        }
        .van-field__control {
          padding: 6px;
        }
      }
    }
  }
  .weaving-warehouse-btn {
    padding: 16px;
    &.van-hairline--top-bottom::after,
    .van-hairline-unset--top-bottom::after {
      border-width: 0;
    }
  }
}
</style>

